package com.certification.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.certification.dto.CertificationDTO;
import com.certification.entity.Certification;
import com.certification.mapper.CertificationMapper;
import com.certification.service.CertRejectService;
import com.certification.service.CertificationService;
import com.certification.vo.CertificationVO;
import com.certification.vo.PageVO;
import com.certification.vo.ResponseMessage;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.certification.constants.CertConstant.*;
import static com.certification.constants.CertStatusConstant.*;


/**
 * @author copa
 * @createDate 2022-03-28 22:14
 * @function
 */
@Service
public class CertificationServiceImpl implements CertificationService {

    @Resource
    private CertificationMapper certificationMapper;

    @Resource
    private CertRejectService certRejectService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<String> addCert(CertificationDTO certificationDTO, Integer userId) {
        Certification certification = new Certification();
        BeanUtils.copyProperties(certificationDTO, certification);
        certification.setPrincipalId(userId);
        int insert = certificationMapper.insert(certification);
        if (insert < 1) {
            return ResponseMessage.errorMsg("系统异常，请稍后再试~");
        }
        return ResponseMessage.successMsg("认证申请信息已保存~等待审核~");
    }

    @Override
    public ResponseMessage<CertificationVO> getCert(Integer certStage, Integer userId) {
        Certification cert = getCertByCertStageAndPrincipalId(CERTIFICATION, userId);
        CertificationVO certificationVO = new CertificationVO();
        BeanUtils.copyProperties(cert, certificationVO);
        certificationVO.setStartTime(cert.getCreateTime());
        return ResponseMessage.success(certificationVO);
    }

    @Override
    public Certification getCertByCertStageAndPrincipalId(Integer certStage, Integer principalId) {
        LambdaQueryWrapper<Certification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != certStage, Certification::getCertStage, certStage)
                .eq(null != principalId, Certification::getPrincipalId, principalId)
                .orderByDesc(true, Certification::getId).last("LIMIT 1");
        return certificationMapper.selectOne(wrapper);
    }

    @Override
    public Certification getOneCertByCertStageAndPrincipalId(Integer certStage,
                                                             Integer principalId,
                                                             Integer certId,
                                                             Integer certStatus) {
        LambdaQueryWrapper<Certification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != certStage, Certification::getCertStage, certStage)
                .eq(null != principalId, Certification::getPrincipalId, principalId)
                .eq(null != certId, Certification::getId, certId)
                .eq(null != certStatus, Certification::getCertStatus, certStatus)
                .orderByDesc(true, Certification::getId).last("LIMIT 1");
        return certificationMapper.selectOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<String> putCert(CertificationDTO certificationDTO, Integer userId) {
        Certification certification = getOneCertByCertStageAndPrincipalId(
                CERTIFICATION, userId, certificationDTO.getId(), CERTING);
        if (Objects.isNull(certification)) {
            return ResponseMessage.errorMsg("该认证记录现阶段不能修改！");
        }
        BeanUtils.copyProperties(certificationDTO, certification);
        int update = certificationMapper.updateById(certification);
        if (update < 1) {
            return ResponseMessage.errorMsg("系统异常~请稍后再试~");
        }
        return ResponseMessage.successMsg("修改申请成功~请等待审核~");
    }

    @Override
    public ResponseMessage<Certification> getCertDetail(Integer certId, Integer userId) {
        return ResponseMessage.success(getOneCertByCertStageAndPrincipalId(CERTIFICATION, userId, certId, null));
    }

    @Override
    public ResponseMessage<List<Certification>> certList() {
        LambdaQueryWrapper<Certification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(true, Certification::getCertStatus, CERTING)
                .orderByDesc(true, Certification::getId);
        return ResponseMessage.success(certificationMapper.selectList(wrapper));
    }

    @Override
    public ResponseMessage<Certification> getCertDetailAdmin(Integer certId) {
        Certification certification = certificationMapper.selectById(certId);
        if (CERTIFICATION == certification.getCertStage()) {
            return ResponseMessage.success(certification);
        }
        return ResponseMessage.errorMsg("请求数据错误~");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage<String> putCertAdmin(Integer certId, Integer status,
                                                String remark, Integer certStage) {
        Certification certification = certificationMapper.selectById(certId);
        if (!certStage.equals(certification.getCertStage())
                || !CERTING.equals(certification.getCertStatus())) {
            return ResponseMessage.errorMsg("该认证记录现阶段不能审核！");
        }
        certification.setCertStatus(status == 1 ? CERT_SUCCESS : CERT_FAIL)
                .setId(certId);
        if (status == 1) {
            switch (certStage) {
                case CERTIFICATION:
                    certification.setCertRemark(remark);
                    break;
                case PROFESSION_SELF_EVALUATION:
                    certification.setProRemark(remark);
                    break;
                case CORRECT_IMPROVE:
                    certification.setImproveRemark(remark);
                    break;
            }
        }

        int update = certificationMapper.updateById(certification);
        if (0 < update  && 2 == status) {
            ResponseMessage<String> certRejectResponseMessage = certRejectService.add(certId, remark);
            if (certRejectResponseMessage.isNotSuccess()) {
                return certRejectResponseMessage;
            }
        }
        return ResponseMessage.successMsg("操作成功~");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer put(Certification cert) {
        return certificationMapper.updateById(cert);
    }

    @Override
    public ResponseMessage<String> certResult(Integer userId) {
        Map<String, Object> resultMap = certificationMapper.selectCertResult(userId);
        if (SCHOOL_INVESTIGATE == Integer.parseInt(resultMap.get("certStage").toString())
                && Integer.parseInt(String.valueOf(resultMap.get("certStatus"))) > 1) {
            int status = Integer.parseInt(String.valueOf(resultMap.get("certStatus")));
            return ResponseMessage.success(status == 2 ? "success" : "fail");
        }
        return ResponseMessage.success("暂时还没有结论噢~");
    }

    @Override
    public ResponseMessage<Page<Certification>> certListPage(PageVO pageVO) {
        LambdaQueryWrapper<Certification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(true, Certification::getCertStatus, CERTING)
                .orderByDesc(true, Certification::getId);

        return ResponseMessage.success(certificationMapper.selectPage(new Page<>(pageVO.getPageNum(), pageVO.getPageSize()), wrapper));
    }

    @Override
    public ResponseMessage<Page<Certification>> getCertDetailAdminPage(Integer certId, PageVO pageVO) {
        QueryWrapper<Certification> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", certId);
        Page<Certification> certificationPage = certificationMapper.selectPage(new Page<>(pageVO.getPageNum(), pageVO.getPageSize()), queryWrapper);
        //Certification certification = certificationMapper.selectById(certId);
        if (Objects.isNull(certificationPage.getRecords()) || certificationPage.getRecords().isEmpty()) {
            return ResponseMessage.success(certificationPage);
        }
        if (CERTIFICATION == certificationPage.getRecords().get(0).getCertStage()) {
            return ResponseMessage.success(certificationPage);
        }
        return ResponseMessage.errorMsg("请求数据错误~");
    }

    @Override
    public Certification getCertById(Integer certId) {
        return certificationMapper.selectById(certId);
    }


}
